package pl.edu.pw.MidEmu.Sensing.Processing;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Arrays;

/**
 * Simple diagnostic class used to test Sebnsor Server
 * 
 * @author Mateusz Starodab
 *
 */
public class SensorPooler extends Thread
{
	private String currentReading;
	private int poolingTime;
	private int port;

	private boolean terminate = true;

	/**
	 * Constuctor
	 * @param port Port on whioch to connect to sensor server
	 * @param poolingTime Interval time between calls to sensor server
	 */
	public SensorPooler(int port, int poolingTime)
	{
		this.poolingTime = poolingTime;
		this.port = port;
	}

	/**
	 * Reads Sensor reading
	 * @return Sensor reading
	 */
	public String getCurrentReading()
	{
		return currentReading;
	}

	/**
	 * Method responsible for continueous pooling sensor server is separate thread
	 */
	@Override
	public void run()
	{
		while (terminate)
		{
			try
			{
				Socket clientSocket = new Socket();
				clientSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(), port));
				BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

				char[] buffer = new char[1024];
				int charRead;
				StringBuilder sb = new StringBuilder();
				while ((charRead = reader.read(buffer)) != -1)
				{
					sb.append(Arrays.copyOfRange(buffer, 0, charRead));
				}

				currentReading = sb.toString();

				reader.close();
				clientSocket.close();

				sleep(poolingTime);
			}
			catch (Exception e)
			{
				terminate = false;
				e.printStackTrace();
			}
		}
	}

	/**
	 * Terminates sensor pooler
	 */
	public void terminate()
	{
		terminate = false;
	}
}
